import hashlib
import logging

from django.db.models import Q, Sum
from django.db.models.query import QuerySet

from apps.usermanager.models import User, UserPermission, Permission, Follow, UserKeyWord
from comment.errorcode import *
from utils.esutils import *


def paging(data_list, page, size):
    """
    分页
    :param data_list:数据列表
    :param page:页数
    :param size:页长度
    :return:
    """
    ret = {
        'page': page, 'size': size, 'total_page': 0, 'total_size': 0
    }
    total_size = len(data_list)
    if total_size % size == 0:
        total_page = total_size / size
    else:
        total_page = total_size / size + 1
    start_index = (page - 1) * size
    end_index = page * size
    
    ret['total_page'] = total_page
    ret['total_size'] = total_size
    if end_index > len(data_list):
        ret['result'] = data_list[start_index:]
        ret["end"] = False
    else:
        ret["end"] = True
        ret['result'] = data_list[start_index: end_index]
    return ret


# user

# 增
def user_add(**kwargs):
    """
    添加用户
    :param request:
    :return:
    """
    name = kwargs.get("name")
    phone = kwargs.get("phone")
    password = kwargs.get("password")
    email = kwargs.get("email")
    is_admin = kwargs.get("is_admin")
    profession = kwargs.get("profession")
    photo = kwargs.get("photo")
    detail = kwargs.get("detail")
    
    try:
        user = User.objects.get(name=name, phone=phone)
        if not user is None:
            return ErrorMsg(CREATE_HAD)
    except Exception as e:
        pass
    
    try:
        result = User.objects.create(name=name, phone=phone, password=password, email=email,
                                     is_admin=is_admin, photo=photo, profession=profession, detail=detail,
                                     create_time=datetime.now())
    except Exception as e:
        logging.error(e)
        return ErrorMsg(CREATE_ERROR)
    
    if result:
        return result
    else:
        return ErrorMsg(CREATE_ERROR)


# 删
def user_del(request):
    """
    通过id删除用户
    :param request:
    :return:
    """
    id = request.POST.get("id")
    user = User.objects.get(id)
    if len(user) == 0:
        return ErrorMsg(SELECT_ERROR, "")
    
    try:
        user.delete()
        return [DELETE_OK, "删除成功", "", 1]
    except Exception as e:
        logging.error(e)
        return ErrorMsg(DELETE_ERROR, "删除失败")


# 改
def user_update(**kwargs):
    """
    修改用户
    :param request:
    :return:
    """
    id = kwargs.get("id")
    name = kwargs.get("name")
    phone = kwargs.get("phone")
    password = kwargs.get("password")
    email = kwargs.get("email")
    is_admin = kwargs.get("is_admin") == "true"
    profession = kwargs.get("profession")
    detail = kwargs.get("detail")
    
    photo = kwargs.get("photo")
    if all([id, name, phone, password, email, is_admin]):
        return ErrorMsg(PARAMS_EMPTY, "参数不全")
    try:
        if photo:
            result = User.objects.filter(id=id).update(name=name, phone=phone, password=password, email=email,
                                                       is_admin=is_admin, photo=photo, profession=profession,
                                                       detail=detail)
        else:
            result = User.objects.filter(id=id).update(name=name, phone=phone, password=password, email=email,
                                                       is_admin=is_admin, profession=profession, detail=detail)
    except Exception as e:
        logging.error(e)
        return ErrorMsg(UPDATE_ERROR, "修改user失败")
    if result != 0:
        return User.objects.get(id=id)
    else:
        return ErrorMsg(UPDATE_ERROR, "修改user失败")


# 查
def user_list(request):
    """
    查询用户
    :param request:
    :return:
    """
    is_admin = request.session.get("is_admin")
    if not is_admin:
        return ErrorMsg(SELECT_ERROR, "没有权限查询")


def user_info(user_id):
    """
    通过id获得用户信息
    :param request:
    :return:
    """
    try:
        user = User.objects.get(id=user_id)
    except Exception as e:
        logging.error(e)
        return ErrorMsg(SELECT_ERROR, "查询不到用户")
    if user is None:
        return ErrorMsg(SELECT_ERROR, "未查询到此用户")
    else:
        return user


def login(request):
    """
    登录
    :param request:
    :return:
    """
    name = request.POST.get("name")
    users = User.objects.get(Q(name=name) | Q(phone=name) | Q(email=name))
    if len(users) == 0:
        return ErrorMsg(LOGIN_EMPTY, "未查询到此用户")
    
    password = request.POST.get("password")
    # 密码加密
    md = hashlib.md5()
    md.update(('usercloud' + password + 'democloud').encode('utf-8'))
    password = md.hexdigest()
    for user in users:
        if user.password == password:
            request.seesion["login"] = True
            request.seesion["id"] = user.id
            request.seesion["name"] = user.name
            request.seesion["is_admin"] = user.is_admin
            request.seesion["phone"] = user.phone
            perssion_id = UserPermission.objects.get(user_id=id).permission_id
            perssion = Permission.objects.get(id=perssion_id).level
            request.seesion["perssion"] = perssion
            return [LOGIN_OK, "登陆成功", '']
    return ErrorMsg(LOGIN_ERROR, "用户名或密码错误")


def logout(request):
    """
    登出
    :param request:
    :return:
    """
    del request.seesion["login"]
    del request.seesion["id"]
    del request.seesion["name"]
    del request.seesion["is_admin"]
    del request.seesion["phone"]
    del request.seesion["perssion"]
    return [DELETE_OK, "登出", None]


def user_base_info(request):
    """
    用户基础信息
    :param request:
    :return:
    """
    id = request.seesion["id"]
    name = request.seesion["name"]
    is_admin = request.seesion["is_admin"]
    phone = request.seesion["phone"]
    perssion = request.seesion["perssion"]
    result = {"id": id, "name": name, "is_admin": is_admin, "phone": phone, "perssion": perssion}
    return [SELECT_OK, "用户查询成功", result]


def user_top3():
    """
    前三用户
    :return:
    """
    result = list(User.objects.all().order_by("follow_time").values("name", "id", "profession","url")[:3])
    if len(result) > 3:
        for value in result[0:3]:
            value["url"] = "/usrmanager/user?active=authorInfo"
        return result
    else:
        for value in result[0:3]:
            value["url"] = "/usrmanager/user?active=authorInfo"
        return result


def user_keywords(author_id):
    """
    用户关键字查询
    :param author_id:
    :return:
    """
    try:
        keywords = UserKeyWord.objects.filter(user_id=author_id)
        keyword_list = []
        for keyword in keywords:
            keyword_list.append(keyword.name)
        return keyword_list
    except Exception as e:
        logging.error(e)
        return ErrorMsg(SELECT_ERROR, "查询关键字失败")


def user_keywords_add(user, args):
    """
    用户关键字添加
    :param author_id:
    :return:
    """
    keywords = []
    for arg in args:
        try:
            if UserKeyWord.objects.filter(name=arg, user_id=user).exists():
                keywords.append(arg)
                continue
            else:
                UserKeyWord.objects.create(name=arg, user_id=user)
            keywords.append(arg)
        except Exception as e:
            logging.error(e)
            return ErrorMsg(CREATE_ERROR)
    return keywords


def user_demos_num(user_id):
    """
    用户案例数量
    :param author_id:
    :return:
    """
    user = User.objects.get(id=user_id)
    return Demo.objects.filter(author=user).count()


def download_count(demos):
    """
    下载数量
    :param author_id:
    :return:
    """
    if demos is None:
        return 0
    count = 0
    for demo in demos:
        count += demo.get("download_time") if demo.get("download_time") else 0
    return count


def read_count(demos):
    """
    阅读数量
    :param demos:
    :return:
    """
    if demos is None:
        return 0
    count = 0
    for demo in demos:
        count += demo.get("read_time") if demo.get("read_time") else 0
    return count


def is_follow(user_id, author_id):
    """
    被关注过
    :param user_id:
    :param author_id:
    :return:
    """
    try:
        follow: QuerySet = Follow.objects.filter(from_user_id=User.objects.get(id=user_id), to_user_id=author_id)
        if not follow.exists():
            return False
        return True
    except Exception as e:
        logging.error(e)
        return ErrorMsg(SELECT_ERROR, "查询关注失败")


def follow_add(user_id, author_id):
    """
    添加关注
    :param user_id:
    :param author_id:
    :return:
    """
    try:
        author = User.objects.get(id=author_id)
        follow = Follow.objects.create(from_user_id=User.objects.get(id=user_id), to_user_id=author)
        author.follow_time = author.follow_time + 1
        author.save()
        if not follow.exists():
            return False
        return True
    except Exception as e:
        logging.error(e)
        return ErrorMsg(SELECT_ERROR, "添加关注失败")


def follow_del(user_id, author_id):
    """
    删除关注
    :param user_id:
    :param author_id:
    :return:
    """
    try:
        author = User.objects.get(id=author_id)
        follow: QuerySet = Follow.objects.filter(from_user_id=User.objects.get(id=user_id), to_user_id=author)
        result, count = follow.delete()
        author.follow_time = author.follow_time - 1 if author.follow_time > 0 else 0
        author.save()
        if count == 0:
            return False
        return True
    except Exception as e:
        logging.error(e)
        return ErrorMsg(SELECT_ERROR, "取消关注失败")


def follow_list(user_id,page,size):
    """
    删除关注
    :param user_id:
    :param author_id:
    :return:
    """
    try:
        follow = Follow.objects.filter(from_user_id=User.objects.get(id=user_id)).values("id","name","permission")
        result = paging(follow,page,size)
        return True
    except Exception as e:
        logging.error(e)
        return ErrorMsg(SELECT_ERROR, "取消关注失败")
